package src.core;

import javax.swing.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class GameFrame extends JFrame {
    public static final int WIDTH = 1280;
    public static final int HEIGHT = 500;

    public PrintWriter out; // 用于发送消息到服务器
    public GamePanel gamePanel; // 拼写修正为Panel

    public String ServerIP="127.0.0.1";

    private final AudioManager audioManager;

    public GameFrame() {
        setTitle("| 脏比清除者v1.0 Demo | ");
        setBounds(50, 100, WIDTH, HEIGHT);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        String ip = (String) JOptionPane.showInputDialog(
                null,
                "请输入服务器IP地址:",
                "连接服务器",
                JOptionPane.QUESTION_MESSAGE,
                null,
                null,
                ServerIP  // 默认本地地址
        );

        // 用户点击取消或关闭对话框
        if(ip == null) {
            System.exit(0); // 或者返回默认值
        }
        ServerIP = ip.trim();

        setTitle("| 脏比清除者v1.0 Demo | "+"当前服务器IP地址："+ServerIP);

        // 初始化音频管理器
        audioManager = AudioManager.getInstance();

        // 播放背景音乐
        audioManager.playBackgroundMusic("src/resource/audio/Waking_the_devil.wav");

        audioManager.setShootVolume(0.1f);
        gamePanel = new GamePanel();
        add(gamePanel);
        gamePanel.action();

        setVisible(true);

        connectToServer();
        setupKeyListener();
    }

    private void connectToServer() {
        String hostname = ServerIP;
        int port = 8888;

        try {
            Socket socket = new Socket(hostname, port);
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);

            // 接收玩家ID
            String idMsg = in.readLine();
            if (idMsg.startsWith("ID:")) {
                System.out.println("你已连接到服务器，你的ID是: " + idMsg.substring(3));
                gamePanel.setPlayerId(Integer.parseInt(idMsg.substring(3)));
            }

            // 启动线程接收服务器消息
            new Thread(() -> {
                try {
                    String serverMessage;
                    while ((serverMessage = in.readLine()) != null) {
                        System.out.println("服务器更新: " + serverMessage);
                        // 更新游戏面板中的玩家位置
                        gamePanel.updatePlayerPositions(serverMessage);
                    }
                } catch (IOException e) {
                    System.out.println("与服务器断开连接");
                }
            }).start();

        } catch (UnknownHostException e) {
            JOptionPane.showMessageDialog(this, "服务器未找到: " + hostname, "连接错误", JOptionPane.ERROR_MESSAGE);
            System.out.println("服务器未找到: " + hostname);
        } catch (IOException e) {
            JOptionPane.showMessageDialog(this, "连接服务器出错: " + e.getMessage(), "连接错误", JOptionPane.ERROR_MESSAGE);
            System.out.println("连接服务器出错: " + e.getMessage());
        }
    }

    private void setupKeyListener() {
        addKeyListener(new KeyListener() {
            @Override
            public void keyTyped(KeyEvent e) {
                // 不需要实现
            }

            @Override
            public void keyPressed(KeyEvent e) {
                char keyChar = Character.toUpperCase(e.getKeyChar());
                if (keyChar == 'Q') {
                    System.exit(0);
                }
                if ("WASD".indexOf(keyChar) != -1 && out != null) {
                    out.println(keyChar);
                } else {
                    System.out.println("无效输入，请使用WASD移动");
                }
            }

            @Override
            public void keyReleased(KeyEvent e) {
                // 不需要实现
            }
        });
    }

    @Override
    public void dispose() {
        // 清理音频资源
        if (audioManager != null) {
            audioManager.cleanup();
        }
        super.dispose();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(GameFrame::new);
    }
}